/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.books.struts.action;

import com.books.struts.form.LoginActionForm;
import com.books.service.LoginService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;

/**
 *
 * @author kinglian
 */
public class LoginAction extends org.apache.struts.action.Action {
    
    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";
    private static final Logger log = Logger.getLogger(LoginAction.class);
    
    /*The service is injected by Spring via IoC */
    private LoginService loginService;

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //get the messages from the ApplicationResources.properties
        MessageResources messages = getResources(request);

        //add errors messages to the target page if there are anything wrong
        ActionMessages errors = new ActionMessages();

        LoginActionForm loginForm = (LoginActionForm)form;

        if (loginService.login(loginForm.getName(), loginForm.getPassword()))
            return mapping.findForward(SUCCESS);
        else
        {
            errors.add("name", new ActionMessage("login.action.failed"));
            this.saveErrors(request, errors);
            return mapping.findForward(FAILURE);
        }
    }
}
